<template>
  <div class="report-list">
    <!-- 创建/编辑报表对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '创建报表' : '编辑报表'"
      width="700px"
    >
      <el-form
        ref="formRef"
        :model="reportForm"
        :rules="formRules"
        label-width="120px"
      >
        <el-form-item label="报表名称" prop="name">
          <el-input v-model="reportForm.name" placeholder="请输入报表名称" />
        </el-form-item>
        <el-form-item label="报表类型">
          <el-input value="表格报表" disabled />
        </el-form-item>
        <el-form-item label="查询SQL" prop="query_sql">
          <el-input
            v-model="reportForm.query_sql"
            type="textarea"
            :rows="4"
            placeholder="请输入查询SQL"
          />
        </el-form-item>
        <el-form-item label="调度配置" prop="schedule_config">
          <el-input
            v-model="scheduleConfigText"
            type="textarea"
            :rows="3"
            placeholder="请输入调度配置JSON"
            @input="updateScheduleConfig"
          />
        </el-form-item>
        <el-form-item label="描述" prop="description">
          <el-input
            v-model="reportForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入描述"
          />
        </el-form-item>
        <el-form-item label="输出格式">
          <el-select v-model="reportForm.output_format" placeholder="请选择输出格式" style="width: 100%">
            <el-option label="CSV" value="CSV" />
            <el-option label="EXCEL" value="EXCEL" />
            <el-option label="HTML" value="HTML" />
            <el-option label="JSON" value="JSON" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="is_active">
          <el-switch v-model="reportForm.is_active" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <el-card class="page-card">
      <template #header>
        <div class="card-header">
          <span>报表管理</span>
        </div>
      </template>

      <!-- 顶部统计卡片 -->
      <div class="data-stats">
        <el-row :gutter="20">
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-primary">
              <div class="stat-item">
                <div class="stat-value">{{ reportStats.total }}</div>
                <div class="stat-label">总报表数</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-success">
              <div class="stat-item">
                <div class="stat-value">{{ reportStats.active }}</div>
                <div class="stat-label">启用报表</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-warning">
              <div class="stat-item">
                <div class="stat-value">{{ reportStats.inactive }}</div>
                <div class="stat-label">禁用报表</div>
              </div>
            </el-card>
          </el-col>
          <el-col :span="6">
            <el-card shadow="hover" class="stat-card accent-info">
              <div class="stat-item">
                <div class="stat-value">{{ reportStats.csvCount }}</div>
                <div class="stat-label">CSV 格式</div>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filter-section card-section">
        <div class="section-header">
          <h3 class="section-title">筛选条件</h3>
        </div>
        <el-row :gutter="20">
          <el-col :span="6">
            <el-input
              v-model="filters.search"
              placeholder="搜索报表名称或描述"
              clearable
              @input="handleSearch"
            >
              <template #prefix>
                <el-icon><Search /></el-icon>
              </template>
            </el-input>
          </el-col>
          <el-col :span="4">
            <el-select v-model="filters.status" placeholder="状态" clearable @change="handleFilter">
              <el-option label="全部" value="" />
              <el-option label="启用" value="true" />
              <el-option label="禁用" value="false" />
            </el-select>
          </el-col>
          <el-col :span="6">
            <el-date-picker
              v-model="filters.dateRange"
              type="daterange"
              range-separator="至"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="YYYY-MM-DD"
              value-format="YYYY-MM-DD"
            />
          </el-col>
          <el-col :span="4">
            <div class="filter-actions">
              <el-button type="primary" @click="handleFilter">筛选</el-button>
              <el-button @click="clearFilters">清除</el-button>
            </div>
          </el-col>
          
        </el-row>
      </div>
      
      <!-- 表格工具栏 -->
      <div class="table-toolbar card-section">
        <div class="section-header">
          <h3 class="section-title">操作工具栏</h3>
        </div>
        <div class="toolbar-content">
          <div class="left">
            <el-button type="success" size="small" @click="handleBatchExecute">批量执行</el-button>
            <el-button size="small" @click="exportSelectedReports">批量导出</el-button>
            <el-button type="warning" size="small" @click="handleBatchEnable">批量启用</el-button>
          </div>
          <div class="right">
            <el-button type="primary" size="small" @click="showAddDialog">创建报表</el-button>
            <el-button size="small" @click="refreshReports">刷新</el-button>
            <el-dropdown @command="handleColumnToggle">
              <el-button size="small">
                列设置 <el-icon><ArrowDown /></el-icon>
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item 
                    v-for="col in availableColumns" 
                    :key="col.prop"
                    :command="col.prop"
                  >
                    <el-checkbox 
                      v-model="col.visible" 
                      @change="toggleColumn(col.prop)"
                    >
                      {{ col.label }}
                    </el-checkbox>
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </div>
      </div>
      
      <el-card class="table-card">
        <template #header>
          <div class="section-header">
            <h3 class="section-title">报表列表</h3>
          </div>
        </template>
        <el-table :data="reports" style="width: 100%" v-loading="loading" @selection-change="onSelectionChange">
          <el-table-column type="selection" width="50" />
          <el-table-column prop="name" label="报表名称" />
          <el-table-column prop="report_type" label="报表类型" width="110">
            <template #default>
              <el-tag size="small">表格报表</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="output_format" label="输出格式" width="110">
            <template #default="{ row }">
              <el-tag size="small">{{ row.output_format || 'CSV' }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="is_active" label="状态" width="100">
            <template #default="{ row }">
              <el-tag :type="row.is_active ? 'success' : 'danger'" size="small">
                {{ row.is_active ? '启用' : '禁用' }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="created_at" label="创建时间" width="180">
            <template #default="{ row }">
              {{ formatTime(row.created_at) }}
            </template>
          </el-table-column>
          <el-table-column label="操作" width="240">
            <template #default="{ row }">
              <ActionMenu
                :actions="[
                  { label: '查看', onClick: () => viewReport(row) },
                  { label: '预览', onClick: () => previewReport(row) },
                  { label: '执行', onClick: () => executeReport(row) },
                  { label: '导出', onClick: () => exportSingleReport(row) },
                  { label: '编辑', onClick: () => editReport(row) },
                  { label: '删除', onClick: () => deleteReport(row) }
                ]"
                :primary-count="2"
              />
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-card>
  </div>
  <!-- 预览对话框 -->
  <el-dialog v-model="previewDialogVisible" title="报表预览" width="800px">
    <template v-if="previewType === 'CSV'">
      <pre style="white-space: pre-wrap;">{{ previewContent }}</pre>
    </template>
    <template v-else-if="previewType === 'HTML'">
      <iframe :srcdoc="previewHtml" style="width:100%;height:420px;border:1px solid #eee;"></iframe>
    </template>
    <template v-else-if="previewType === 'JSON'">
      <pre style="white-space: pre-wrap;">{{ JSON.stringify(previewJson, null, 2) }}</pre>
    </template>
    <template v-else-if="previewType === 'EXCEL'">
      <el-table :data="previewExcel.slice(1).map((row, idx) => Object.fromEntries(previewExcel[0].map((h,i)=>[h,row[i]])))" style="width:100%">
        <el-table-column v-for="(h, i) in previewExcel[0]" :key="i" :prop="String(h)" :label="String(h)" />
      </el-table>
    </template>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="previewDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
  
  <!-- 查看详情对话框 -->
  <el-dialog v-model="viewDialogVisible" title="报表详情" width="720px">
    <el-descriptions :column="2" border>
      <el-descriptions-item label="名称">{{ currentReport?.name }}</el-descriptions-item>
      <el-descriptions-item label="类型">表格报表</el-descriptions-item>
      <el-descriptions-item label="输出格式">{{ currentReport?.output_format || 'CSV' }}</el-descriptions-item>
      <el-descriptions-item label="状态">
        <el-tag :type="currentReport?.is_active ? 'success' : 'danger'" size="small">
          {{ currentReport?.is_active ? '启用' : '禁用' }}
        </el-tag>
      </el-descriptions-item>
      <el-descriptions-item label="创建时间">{{ formatTime(currentReport?.created_at as any) }}</el-descriptions-item>
      <el-descriptions-item label="更新时间">{{ formatTime(currentReport?.updated_at as any) }}</el-descriptions-item>
      <el-descriptions-item label="描述" :span="2">{{ currentReport?.description || '-' }}</el-descriptions-item>
      <el-descriptions-item label="查询SQL" :span="2">
        <pre style="white-space: pre-wrap; margin:0;">{{ currentReport?.query_sql }}</pre>
      </el-descriptions-item>
      <el-descriptions-item label="调度配置" :span="2">
        <pre style="white-space: pre-wrap; margin:0;">{{ JSON.stringify(currentReport?.schedule_config || {}, null, 2) }}</pre>
      </el-descriptions-item>
    </el-descriptions>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="viewDialogVisible = false">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { reportApi } from '@/api/report'
import { exportToCSV } from '@/utils/export'
import type { Report } from '@/types'
import { Search, ArrowDown } from '@element-plus/icons-vue'
import ActionMenu from '@/components/ActionMenu.vue'

// 响应式数据
const reports = ref<Report[]>([])
const loading = ref(false)
const dialogVisible = ref(false)
const dialogType = ref<'add' | 'edit'>('add')
const formRef = ref<FormInstance>()

// 筛选条件
const filters = reactive({
  search: '',
  status: '',
  dateRange: [] as string[]
})

// 列设置
const availableColumns = ref([
  { prop: 'name', label: '报表名称', visible: true },
  { prop: 'report_type', label: '报表类型', visible: true },
  { prop: 'description', label: '描述', visible: true },
  { prop: 'is_active', label: '状态', visible: true },
  { prop: 'created_at', label: '创建时间', visible: true }
])

// 统计卡片数据
const reportStats = computed(() => {
  const total = reports.value.length
  const active = reports.value.filter(r => r.is_active).length
  const inactive = reports.value.filter(r => !r.is_active).length
  const csvCount = reports.value.filter(r => (r.output_format || 'CSV') === 'CSV').length
  return { total, active, inactive, csvCount }
})

// 筛选后的报表数据
const filteredReports = computed(() => {
  let result = reports.value
  
  if (filters.search) {
    const searchLower = filters.search.toLowerCase()
    result = result.filter(report => 
      report.name?.toLowerCase().includes(searchLower) ||
      report.description?.toLowerCase().includes(searchLower)
    )
  }
  
  // report_type 固定为 table，无需过滤
  
  if (filters.status !== '') {
    const statusBool = filters.status === 'true'
    result = result.filter(report => report.is_active === statusBool)
  }
  
  if (filters.dateRange && filters.dateRange.length === 2) {
    const [startDate, endDate] = filters.dateRange
    result = result.filter(report => {
      if (!report.created_at) return false
      const createDate = report.created_at.split('T')[0]
      return createDate >= startDate && createDate <= endDate
    })
  }
  
  return result
})

// 搜索处理
const handleSearch = () => {
  // 实时搜索，不需要额外处理
}

// 筛选处理
const handleFilter = () => {
  // 筛选逻辑已在计算属性中处理
}

// 清除筛选
const clearFilters = () => {
  filters.search = ''
  filters.status = ''
  filters.dateRange = []
}

// 多选与批量导出
const selectedReports = ref<Report[]>([])
const onSelectionChange = (rows: Report[]) => { selectedReports.value = rows }
const exportSelectedReports = () => {
  if (!selectedReports.value.length) {
    ElMessage.info('请先选择要导出的报表')
    return
  }
  const rows = selectedReports.value.map(r => ({
    报表名称: r.name,
    报表类型: getReportTypeText(r.report_type),
    状态: r.is_active ? '启用' : '禁用',
    创建时间: formatTime(r.created_at)
  }))
  exportToCSV(rows, { filename: '选中报表' })
}

// 单个导出
const exportSingleReport = (report: Report) => {
  const rows = [{
    报表名称: report.name,
    报表类型: getReportTypeText(report.report_type),
    状态: report.is_active ? '启用' : '禁用',
    创建时间: formatTime(report.created_at)
  }]
  exportToCSV(rows, { filename: `${report.name}-报表` })
}

// 批量启用
const handleBatchEnable = () => {
  ElMessage.info('批量启用功能开发中...')
}

// 刷新报表
const refreshReports = () => {
  loadReports()
}

// 列设置
const handleColumnToggle = (prop: string) => {
  // 列切换逻辑
}

const toggleColumn = (prop: string) => {
  // 切换列显示/隐藏
}

// 获取列显示状态
const getColumnVisible = (prop: string): boolean => {
  const column = availableColumns.value.find(col => col.prop === prop)
  return column ? column.visible : true
}

// 表单数据
const reportForm = ref<Partial<Report>>({
  name: '',
  report_type: 'table',
  query_sql: '',
  schedule_config: {},
  description: '',
  is_active: true,
  output_format: 'CSV'
})

// 调度配置文本（用于显示）
const scheduleConfigText = ref('')

const updateScheduleConfig = () => {
  try {
    reportForm.value.schedule_config = JSON.parse(scheduleConfigText.value)
  } catch (error) {
    // 如果JSON解析失败，保持原值
  }
}

// 表单验证规则
const formRules: FormRules = {
  name: [
    { required: true, message: '请输入报表名称', trigger: 'blur' }
  ],
  report_type: [
    { required: true, message: '请选择报表类型', trigger: 'change' }
  ],
  query_sql: [
    { required: true, message: '请输入查询SQL', trigger: 'blur' }
  ],
  output_format: [
    { required: true, message: '请选择输出格式', trigger: 'change' }
  ]
}

const loadReports = async () => {
  loading.value = true
  try {
    const response = await reportApi.getReports()
    reports.value = response.data.items
  } catch (error) {
    console.error('Failed to load reports:', error)
    ElMessage.error('加载报表列表失败')
  } finally {
    loading.value = false
  }
}

const showAddDialog = () => {
  dialogType.value = 'add'
  reportForm.value = {
    name: '',
    report_type: 'table',
    query_sql: '',
    schedule_config: {},
    description: '',
    is_active: true,
    output_format: 'CSV'
  }
  scheduleConfigText.value = ''
  dialogVisible.value = true
}

const editReport = (report: Report) => {
  dialogType.value = 'edit'
  reportForm.value = { ...report }
  scheduleConfigText.value = JSON.stringify(report.schedule_config || {}, null, 2)
  dialogVisible.value = true
}

const submitForm = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    
    if (dialogType.value === 'add') {
      await reportApi.createReport(reportForm.value)
      ElMessage.success('创建成功')
    } else {
      await reportApi.updateReport(reportForm.value.id!, reportForm.value)
      ElMessage.success('更新成功')
    }
    
    dialogVisible.value = false
    loadReports()
  } catch (error) {
    console.error('Form submission failed:', error)
    ElMessage.error('操作失败')
  }
}

const viewReport = (report: Report) => {
  currentReport.value = report
  viewDialogVisible.value = true
}

const executeReport = async (report: Report) => {
  try {
    await reportApi.executeReport(report.id)
    ElMessage.success('报表执行成功')
  } catch (error) {
    console.error('Execute report failed:', error)
    ElMessage.error('报表执行失败')
  }
}

const deleteReport = async (report: Report) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除报表 "${report.name}" 吗？`,
      '确认删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    await reportApi.deleteReport(report.id)
    ElMessage.success('删除成功')
    loadReports()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('Delete failed:', error)
      ElMessage.error('删除失败')
    }
  }
}

const handleBatchExecute = () => {
  ElMessage.info('批量执行功能开发中...')
}

const getReportTypeText = (type: string): string => {
  const texts: Record<string, string> = {
    'table': '表格报表',
    'chart': '图表报表',
    'dashboard': '仪表板'
  }
  return texts[type] || type
}

const formatTime = (time: string): string => {
  if (!time) return '-'
  return new Date(time).toLocaleString('zh-CN')
}

const previewDialogVisible = ref(false)
const previewContent = ref('')
const previewHtml = ref('')
const previewJson = ref<any>(null)
const previewExcel = ref<any[][]>([])
const previewType = ref<'CSV' | 'HTML' | 'JSON' | 'EXCEL'>('CSV')

const previewReport = async (report: Report) => {
  const fmt = (report.output_format || 'CSV') as 'CSV' | 'HTML' | 'JSON' | 'EXCEL'
  previewType.value = fmt
  const res = await reportApi.previewReport(report.id, fmt)
  previewContent.value = ''
  previewHtml.value = ''
  previewJson.value = null
  previewExcel.value = []
  if (fmt === 'CSV') {
    previewContent.value = res.data as string
  } else if (fmt === 'HTML') {
    previewHtml.value = res.data as string
  } else if (fmt === 'JSON') {
    previewJson.value = res.data
  } else if (fmt === 'EXCEL') {
    previewExcel.value = res.data as any[][]
  }
  previewDialogVisible.value = true
}

const viewDialogVisible = ref(false)
const currentReport = ref<Report | null>(null)

onMounted(() => {
  loadReports()
})
</script>

<style scoped>
.filter-actions {
  display: flex;
  align-items: center;
  justify-content: flex-end;
  gap: 8px;
  flex-wrap: nowrap;
}

.table-toolbar {
  margin: 0 0 16px;
}
.toolbar-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.report-list {
  padding: 0;
}

.page-card {
  background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%);
  border: 1px solid #eef2f6;
  border-radius: 12px;
  box-shadow: 0 4px 16px rgba(31,35,41,0.06);
}
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding-bottom: 6px;
  border-bottom: 1px dashed #eef2f6;
}

.data-stats { margin-bottom: 20px; }
.stat-card { text-align: center; border-left: 4px solid var(--accent, #409EFF); background: linear-gradient(180deg, var(--accent-bg, #f0f7ff) 0%, #ffffff 40%); }
.stat-card.accent-primary { --accent:#409eff; --accent-bg:#f0f7ff; }
.stat-card.accent-success { --accent:#67C23A; --accent-bg:#ecfdf5; }
.stat-card.accent-warning { --accent:#E6A23C; --accent-bg:#fdf6ec; }
.stat-card.accent-info { --accent:#909399; --accent-bg:#f3f4f6; }
.stat-item { padding: 20px; }
.stat-value { font-size: 24px; font-weight: 800; margin-bottom: 8px; color: var(--accent, #409EFF); }
.stat-label { color: #606266; font-size: var(--font-subtitle); }

.card-section { background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); padding: 16px; margin-bottom: 16px; }
.section-header { display: flex; justify-content: space-between; align-items: center; padding-bottom: 6px; margin-bottom: 8px; border-bottom: 1px dashed #eef2f6; }
.section-title { margin: 0; font-size: var(--font-title); font-weight: 700; color: #1f2937; }

.table-card { margin-top: 8px; background: linear-gradient(180deg, #ffffff 0%, #fafcfe 100%); border: 1px solid #eef2f6; border-radius: 12px; box-shadow: 0 4px 16px rgba(31,35,41,0.06); }

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 